package com.bbcare.followup.plat.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aliyun.openservices.shade.com.alibaba.rocketmq.shade.io.netty.util.internal.StringUtil;
import com.bbcare.comm.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.followup.plat.entity.BodyTemperature;
import com.bbcare.followup.plat.entity.BodyTemperatureanalysis;
import com.bbcare.followup.plat.entity.BodyTemperaturedetail;
import com.bbcare.followup.plat.entity.Oxygenpulserate;
import com.bbcare.followup.plat.entity.Oxygenpulserateanalysis;
import com.bbcare.followup.plat.entity.Oxygenpulseratedetail;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.service.IFamilyReportService;
import com.bbcare.followup.plat.service.IPatientInfoHisService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.service.IPatientqueryCardService;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;

/**
 * @name: 同步数据
 * @author: DemonLee
 * @createTime: 2017.5.12
 * @description:
 * @modify:
 * 
 */
@Controller
@RequestMapping("/webapi/service/synch")
public class SynchDataCtroller {
    private final Log logger = LogFactory.getLog(SynchDataCtroller.class);

    @Autowired
    private IPatientService patientSerivce;
    
    @Autowired
    private IPatientInfoHisService patientInfoHisService;
    
    @Autowired
    private IPatientqueryCardService patientqueryCardService;
    
    @Autowired
    private IFamilyReportService familyReportService;
    
    @Autowired
	IPatientDAO patientdao;
    
    // 根据门诊号查询患者信息List
    @ResponseBody
    @RequestMapping("/querySynchData")
    public ResultModel<Map<String, Object>> querySynchData(@RequestBody String arg) throws Exception {
        logger.warn("in querySynchData----arg==" + arg);

        JSONObject jsonEsb = null;
        try {
        	jsonEsb = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

        String phoneNo = requestParam.getString("phoneNo");
        if (null == phoneNo || "".equals(phoneNo)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入服务号码或值为空！"));
        }
        
        String IDiccid = requestParam.getString("IDiccid");
        if (null == IDiccid || "".equals(IDiccid)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入证件或值为空！"));
        }
        
        HashMap<String, Object> servParamMap = new HashMap<String, Object>();
        servParamMap.put("phoneNo", phoneNo);
        servParamMap.put("IDiccid", IDiccid);
        List<Map<String, Object>> lists= new ArrayList<Map<String, Object>>();
        //服务号码查不到值用证件号码查询
        List<Map<String, Object>> list = patientqueryCardService.getcardInfo(servParamMap);
        if(list.size()<0||list.isEmpty()){
         lists = patientSerivce.getPatientInfoByOutNo(servParamMap);
        }
        //HashMap<String, Object> retMap = new HashMap<String, Object>();
       // HashMap<String, Object> retMap = new HashMap<String, Object>();
//        HashMap<String, Object> retMap = new HashMap<String, Object>();
        /*
         * int total = 0; if (null != list) { total = list.size(); }
         * retMap.put("rows", list); retMap.put("total", total);
         */
        if (null != list && 0 != list.size()) {
            return new ResultModel<Map<String, Object>>(list.get(0));
        } else {
        	  return new ResultModel<Map<String, Object>>(lists.get(0));
        }
    }

    // 根据门诊号更新患者信息
    @ResponseBody
    @RequestMapping("/commitSynchData")
    public ResultModel<HashMap<String, Object>> commitSynchData(@RequestBody String arg) throws Exception {
        /*logger.warn("in commitSynchData----arg==" + arg);

        JSONObject jsonEsb = null;
        try {
        	jsonEsb = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonEsb = JSON.parseObject(arg);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}
		
		channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆
		String phoneNo = requestParam.getString("phoneNo");
		if(null == phoneNo||phoneNo.equals("")){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "phoneNo传入为空或者传入值不正确!");
    	}
		*/
       // HashMap<String, Object> paramMap = new HashMap<String, Object>();
       /* paramMap.put("id", requestParam.getString("id"));
        paramMap.put("phoneNo", requestParam.getString("phoneNo"));
        paramMap.put("outpatno", requestParam.getString("outpatno"));
        paramMap.put("zjhm", requestParam.getString("zjhm"));
        paramMap.put("fmhfyrxm", requestParam.getString("fmhfyrxm"));
        paramMap.put("fmzy", requestParam.getString("fmzy"));
        paramMap.put("fmwhcd", requestParam.getString("fmwhcd"));
        paramMap.put("wyfs", requestParam.getString("wyfs"));
        paramMap.put("rgwyz", requestParam.getString("rgwyz"));
        paramMap.put("wycs", requestParam.getString("wycs"));
        paramMap.put("wyl", requestParam.getString("wyl"));
        paramMap.put("dnsj", requestParam.getString("dnsj"));
        paramMap.put("tjfspsj", requestParam.getString("tjfspsj"));
        paramMap.put("tjfspzl", requestParam.getString("tjfspzl"));
        paramMap.put("ywwykn", requestParam.getString("ywwykn"));
        paramMap.put("dbcs", requestParam.getString("dbcs"));
        paramMap.put("dbcs2", requestParam.getString("dbcs2"));
        paramMap.put("bz", requestParam.getString("bz"));
        paramMap.put("ywgm", requestParam.getString("ywgm"));
        paramMap.put("gmyw", requestParam.getString("gmyw"));
        paramMap.put("swgm", requestParam.getString("swgm"));
        paramMap.put("gmsw", requestParam.getString("gmsw"));
        paramMap.put("yfjzs", requestParam.getString("yfjzs"));
        paramMap.put("jzfy", requestParam.getString("jzfy"));
        paramMap.put("jzycbs", requestParam.getString("jzycbs"));
        paramMap.put("jtcrb", requestParam.getString("jtcrb"));*/

        logger.warn("in savePtContDataQuerys----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
   
        String opCode = jsonData.getString("opCode");
        if (null == opCode || "".equals(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无操作编码节点！"));
        }
        String queueId = jsonData.getString("followQueueId");
        if (null == queueId || "".equals(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无队列id节点！"));
        }
        String ptSchemeId = jsonData.getString("ptSchemeId");
        if (null == ptSchemeId || "".equals(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者队列实例id或值为空！"));
        }
        String userId = jsonData.getString("patientId");
        if (null == userId || "".equals(userId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者id未传或值为空！"));
        }
        String phoneNo = jsonData.getString("phoneNo");
        if (null == phoneNo || "".equals(phoneNo)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，服务号码未传或值为空！"));
        }
        String cardNo = jsonData.getString("cardNo");
        if (null == cardNo || "".equals(cardNo)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，卡号未传或值为空！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，是患者自己
        String author = userId;
        Map<String, Object> ptMap = new HashMap<String, Object>();
        ptMap.put("userId", userId);
        List<Patient> ptList = patientSerivce.getPatientList(ptMap);
        if (CollectionUtils.isEmpty(ptList)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "查询随访系统无此患者！"));
        }
        Patient ptVo = ptList.get(0);
        String authorName = ptVo.getUserName();
        String tenantId = "";// 租户id
        paramMap.put("authorName", authorName);

        String taskId = jsonData.getString("ptTaskId");
        if (null == taskId || "".equals(taskId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者任务id或值为空！"));
        }
        
        String zjhm = jsonData.getString("zjhm");
       /* if (null == zjhm || "".equals(zjhm)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入证件号码或值为空！"));
        }*/
        String type = jsonData.getString("type");
        if (StringUtils.isEmpty(type)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，问卷类型不能为空!");
        }
        
        String pathash = jsonData.getString("pathash");
        if (StringUtils.isEmpty(pathash)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，病人识别码 不能为空!");
        }
        
        String bookid = jsonData.getString("bookid");
        if (StringUtils.isEmpty(bookid)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，问卷对应的预约ID 不能为空!");
        }
        
        String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
        paramMap.put("taskId", taskId);
        paramMap.put("contentData", jsonData.getJSONObject("questiones"));
        paramMap.put("ptSchemeId", ptSchemeId);
        paramMap.put("userId", userId);
        paramMap.put("updateTime", currTime);
        paramMap.put("updateAccept", updateAccept);
        paramMap.put("authorId", author);
        paramMap.put("tenantId", tenantId);
        paramMap.put("opCode", opCode);
        paramMap.put("queueId", queueId);
        paramMap.put("opNote", jsonData.getString("opNote"));
        paramMap.put("opType", jsonData.getString("opType"));
        paramMap.put("updateAuname", authorName);
        paramMap.put("type", type);
        paramMap.put("phoneNo", phoneNo);
        paramMap.put("cardNo", cardNo);
        paramMap.put("zhusuType", "Y");
        paramMap.put("zjhm", zjhm);
        paramMap.put("pathash", pathash);
        paramMap.put("bookid", bookid);
        
        patientSerivce.modTaskContentData(paramMap);

        HashMap<String, Object> retMap = new HashMap<String, Object>();
        return new ResultModel<HashMap<String, Object>>(retMap);
    }
    
    //app同步氧饱脉率数据
    @ResponseBody
    @RequestMapping("/oxygenpulserateSynchFromApp")
    public ResultModel<Map<String, Object>> oxygenpulserateSynchData(@RequestBody String arg) throws Exception {
        logger.warn("in oxygenpulserateSynchData----arg==" + arg);

        JSONObject jsonEsb = null;
        try {
        	jsonEsb = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}
		
		//氧饱脉率记录
		Oxygenpulserate oxygenPulserate = JSON.parseObject(requestParam.getString("oxygenPulserate"),Oxygenpulserate.class);
		if(null == oxygenPulserate){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "oxygenPulserate传入为空或者传入值不正确!");
    	}
		
		Oxygenpulserateanalysis oxygenPulserateAnalysis = JSON.parseObject(requestParam.getString("oxygenPulserateAnalysis"),Oxygenpulserateanalysis.class);
		if(null == oxygenPulserateAnalysis){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "oxygenPulserateAnalysis传入为空或者传入值不正确!");
    	}
		
		List<Oxygenpulseratedetail> oxygenPulserateDetails = JSON.parseArray(requestParam.getString("oxygenPulserateDetails"),Oxygenpulseratedetail.class);
		if(null == oxygenPulserateDetails){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "oxygenPulserateDetails传入为空或者传入值不正确!");
    	}
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("oxygenPulserate",oxygenPulserate);
		if(!StringUtils.isEmpty(oxygenPulserate.getUserid()) && StringUtils.isEmpty(oxygenPulserateAnalysis.getUserid()) ){
			oxygenPulserateAnalysis.setUserid(oxygenPulserate.getUserid());
		}
		
		if(!StringUtils.isEmpty(oxygenPulserate.getStartDate()) && StringUtils.isEmpty(oxygenPulserateAnalysis.getTesttime()) ){
			oxygenPulserateAnalysis.setTesttime(DateUtil.getDateA(oxygenPulserate.getStartDate()));
		}
		
		oxygenPulserateAnalysis.setTimelong(oxygenPulserate.getTimelong());
		
		map.put("oxygenPulserateAnalysis",oxygenPulserateAnalysis);
		map.put("oxygenPulserateDetails",oxygenPulserateDetails);
		
		familyReportService.oxygenpulserateSynchData(map);
		
		String userId = oxygenPulserate.getUserid();
		try{
			if(!StringUtils.isEmpty(userId)){
				Map<String,Object> userMap = new HashMap<String,Object>();
				userMap.put("userId", userId);
				Patient pt = patientdao.selectById(userMap);
				
				if(null != pt){
					Map<String,Object> param = new HashMap<String,Object>();
					param.putAll(requestParam);
					param.put("opUsertype",Constants.OPCODE_TYPE_PATIENT);
					param.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_6);
					param.put("authorId",userId);
					param.put("userId",userId);
					
		            String remark = "患者【" + pt.getUserName() + "】上传氧饱脉率监测数据";
		            param.put("remark", remark);
					param.put("updateAccept",SeqUtil.getSeqNo());
					param.put("opCode",Constants.OP_CODE_1008);
					param.put("busiId",oxygenPulserate.getOxygenpulserateid());
					patientInfoHisService.saveOperationRecord(param);


				}
			}
			
		}catch(Exception e){
			logger.error("保存上传氧饱脉率操作记录表报错", e);
		}
        Map<String, Object> retMap = new HashMap<String, Object>();
        return new ResultModel<Map<String, Object>>(retMap);
    }
    
    //app同步体温数据
    @ResponseBody
    @RequestMapping("/bodytemperatureSynchFromApp")
    public ResultModel<Map<String, Object>> bodytemperatureSynchData(@RequestBody String arg) throws Exception {
        logger.warn("in bodytemperatureSynchData----arg==" + arg);

        JSONObject jsonEsb = null;
        try {
        	jsonEsb = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}
		
		//体温记录
		BodyTemperature bodyTemperature = JSON.parseObject(requestParam.getString("bodyTemperature"),BodyTemperature.class);
		if(null == bodyTemperature){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "bodyTemperature传入为空或者传入值不正确!");
    	}
		
		BodyTemperatureanalysis bodyTemperatureanalysis = JSON.parseObject(requestParam.getString("bodyTemperatureAnalysis"),BodyTemperatureanalysis.class);
		if(null == bodyTemperatureanalysis){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "bodyTemperatureanalysis传入为空或者传入值不正确!");
    	}
		
		List<BodyTemperaturedetail> bodyTemperaturedetails = JSON.parseArray(requestParam.getString("bodyTemperatureDetail"),BodyTemperaturedetail.class);
		if(null == bodyTemperaturedetails){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "bodyTemperaturedetails传入为空或者传入值不正确!");
    	}
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("bodyTemperature",bodyTemperature);
		if(!StringUtils.isEmpty(bodyTemperature.getUserid()) && StringUtils.isEmpty(bodyTemperatureanalysis.getUserid()) ){
			bodyTemperatureanalysis.setUserid(bodyTemperature.getUserid());
		}
		
		//没有设置最高温度 默认为38
		if(StringUtils.isEmpty(bodyTemperatureanalysis.getTempalarmtop()) || bodyTemperatureanalysis.getTempalarmtop().doubleValue() <= 0){
			bodyTemperatureanalysis.setTempalarmtop(37d);
		}
		
		map.put("bodyTemperatureanalysis",bodyTemperatureanalysis);
		map.put("bodyTemperaturedetails",bodyTemperaturedetails);
		
		familyReportService.bodyTemperatureSynchData(map);
		
		String userId = bodyTemperature.getUserid();
		try{
			if(!StringUtils.isEmpty(userId)){
				Map<String,Object> userMap = new HashMap<String,Object>();
				userMap.put("userId", userId);
				Patient pt = patientdao.selectById(userMap);
				
				if(null != pt){
					Map<String,Object> param = new HashMap<String,Object>();
					param.putAll(requestParam);
					param.put("opUsertype",Constants.OPCODE_TYPE_PATIENT);
					param.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_6);
					param.put("authorId",userId);
					param.put("userId",userId);
		            String remark = "患者【" + pt.getUserName() + "】上传体温监测数据";
		            param.put("remark", remark);
					param.put("updateAccept",SeqUtil.getSeqNo());
					param.put("opCode",Constants.OP_CODE_1007);
					param.put("busiId",bodyTemperature.getBodytemperatureid());
					patientInfoHisService.saveOperationRecord(param);
				}
				//同步消息
				 bodyTemperature.setFinalvalue(bodyTemperatureanalysis.getFinalvalue());

			}
			
		}catch(Exception e){
			logger.error("保存上传氧饱脉率操作记录表报错", e);
		}
		
        Map<String, Object> retMap = new HashMap<String, Object>();
        return new ResultModel<Map<String, Object>>(retMap);
    }
    
    //app同步生长发育数据
    @ResponseBody
    @RequestMapping("/growthSynchFromApp")
    public ResultModel<Map<String, Object>> growthSynchData(@RequestBody String arg) throws Exception {
        logger.warn("in growthSynchData----arg==" + arg);
        Map<String, Object> retMap = new HashMap<String, Object>();
        JSONObject jsonEsb = null;
        try {
        	jsonEsb = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}
		
		//生长发育
		String testTime = requestParam.getString("testTime");
		if(StringUtils.isEmpty(testTime)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "监测时间传入为空或者传入值不正确!");
    	}
		
		String height = requestParam.getString("height");
		if(StringUtils.isEmpty(height)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "身高传入为空或者传入值不正确!");
    	}
		String weight = requestParam.getString("weight");
		if(StringUtils.isEmpty(weight)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "体重传入为空或者传入值不正确!");
    	}
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("testTime",testTime);
		map.put("height",height);
		map.put("weight",weight);
		map.put("headCircumference",requestParam.getString("headCircumference"));
		map.put("userId",requestParam.getString("userId"));
		map.put("babyId",requestParam.getString("babyId"));
		map.put("tenantId",Constants.PT_USER_INFO_DEFAULT_TENANT_ID);//app个人录入  租户id默认为0
		Map<String,Object> rspMap = familyReportService.addGrowthRecordBySyn(map);
		

		String userId = requestParam.getString("userId");
		try{
			if(!StringUtils.isEmpty(userId)){
				Map<String,Object> userMap = new HashMap<String,Object>();
				userMap.put("userId", userId);
				Patient pt = patientdao.selectById(userMap);
				
				if(null != pt){
					Map<String,Object> param = new HashMap<String,Object>();
					param.putAll(requestParam);
					param.put("opUsertype",Constants.OPCODE_TYPE_PATIENT);
					param.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_6);
					param.put("authorId",userId);
					param.put("userId",userId);
		            String remark = "患者【" + pt.getUserName() + "】上传生长发育监测数据";
		            param.put("remark", remark);
					param.put("updateAccept",SeqUtil.getSeqNo());
					param.put("opCode",Constants.OP_CODE_1011);
					param.put("busiId",rspMap.get("id"));
					patientInfoHisService.saveOperationRecord(param);
				}
			}
			
		}catch(Exception e){
			logger.error("保存上传生长发育操作记录表报错", e);
		}
		
        return new ResultModel<Map<String, Object>>(retMap);
    }
    
    //APP端患者活跃信息录入 
    @ResponseBody
    @RequestMapping("/patientActiveInfoFromApp")
    public ResultModel<Map<String, Object>> patientActiveInfoFromApp(@RequestBody String arg) throws Exception {
        logger.warn("in patientActiveInfoFromApp----arg==" + arg);
        Map<String, Object> retMap = new HashMap<String, Object>();
        JSONObject jsonEsb = null;
        try {
        	jsonEsb = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}
		
		String userId = requestParam.getString("userId");
		if(StringUtils.isEmpty(userId)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "用户ID不能为空!");
		}
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", userId);
		Patient pt = patientdao.selectById(map);
		/*String userName = requestParam.getString("userName");
		if(StringUtils.isEmpty(userName)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "用户姓名不能为空!");
		}*/
		if(null == pt){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,
        			"患者信息不存在");		}
		
		String opCode = requestParam.getString("opCode");
		if(StringUtils.isEmpty(opCode)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "操作类型不能为空!");
		}
		
		Map<String,Object> param = new HashMap<String,Object>();
		param.putAll(requestParam);
		if(Constants.OP_CODE_1016.equals(opCode)){
			param.put("opUsertype",Constants.OPCODE_TYPE_PATIENT);
			param.put("type", Constants.PATIENT_ACTIVE_APP_LOGIN);
			param.put("authorId",userId);
		}
		
		if (StringUtils.isEmpty((String) requestParam.get("opNote"))) {
            String remark = "患者【" + pt.getUserName() + "】登陆app系统";
            param.put("remark", remark);
        } else {
        	param.put("remark", (String) requestParam.get("opNote"));
        }
		param.put("updateAccept",SeqUtil.getSeqNo());
		patientInfoHisService.saveOperationRecord(param);
        return new ResultModel<Map<String, Object>>(retMap);
    }
    
    
    /**
     * @name:查询门诊随访
     * @description:查询门诊随访信息，当前患者还有需要进行几次随访
     * @author: wuyz
     * @date: 2017-07-07
     * @version: 1.0
     * @param:
	 *        channel	:渠道类型  非空  值为：BBCARE-APP <br />
     * 		  groupId	：科室id或者队列id <br />
     * 		  groupType	：队列或者科室id标识 1：科室 ；2：队列  <br />
     * 		  patientId	：患者id <br />
     * 		  quesType	：问卷类型  0：门诊问卷随访 ；1：线上问卷随访
     *
     * @return
     * 
     **/
    @ResponseBody
    @RequestMapping("/queryTaskInfoRemind")
    public ResultModel<Map<String,Object>> queryTaskInfoRemind (@RequestBody String str) throws Exception{
    	
    	logger.info("input ~~ queryTaskInfoRemind"+str);
    	str=URLDecoder.decode(str,"utf-8");
		logger.warn("in 解码---arg==" + str);
    	//接收入参处理成JSONObject
    	JSONObject jb = null;
    	try {
    		jb = JSON.parseObject(str);
		} catch (Exception e) {
			e.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}
    	
    	//取入参根节点date节点下的值
    	JSONObject jsonStr = jb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
    	if(null == jsonStr ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
    	
    	//channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆
		String channel = jsonStr.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}
    	
		//患者id
		String patientId = jsonStr.getString("patientId");
        if (StringUtils.isEmpty(patientId)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者不能为空!");
        }
        
        //队列或者科室id标识
        String groupType = jsonStr.getString("groupType");
        if (StringUtils.isEmpty(groupType)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，组织类型不能为空!");
        }
        
        //科室id或者队列id
        String groupId = jsonStr.getString("groupId");
        if (StringUtils.isEmpty(groupId)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，组织id不能为空!");
        }
        
        //问卷类型 
        String quesType = jsonStr.getString("quesType");
        if (StringUtils.isEmpty(quesType)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，问卷类型不能为空!");
        }
		
        //整合入参
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("patientId", patientId);
        map.put("invokeType", "1");// app调用
        if (Constants.ID_FOR_OFFICE.equals(groupType)) {
            map.put("departmentId", groupId);
        } else if (Constants.ID_FOR_QUEUE.equals(groupType)) {
            map.put("queueId", groupId);
        } else {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，组织类型值未定义!");
        }
        map.put("type", quesType);
        Map<String, Object> rspMap = patientqueryCardService.selectPtOnlineTaskInfo(map);

        return new ResultModel<Map<String, Object>>(rspMap);
    }


}
